package com.t9101DR.dao;


import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;


public class BaseDao {
	private static  String url=null;
	private static  String className=null;
	private static  String userName=null;
	private static  String pwd=null;
	private Connection conn=null;
	
	static {
		Properties prop = new Properties();
		InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
		
		try {
			prop.load(is);
			className=prop.getProperty("drivername");
			url=prop.getProperty("url");
			userName=prop.getProperty("userName");
			pwd=prop.getProperty("pwd");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//�������ݿ�
	
	public Connection getConnection() {
		try {
			if(conn==null||conn.isClosed()) {
				Class.forName(className);
				conn=DriverManager.getConnection(url,userName,pwd);
//				Context ctx = new InitialContext();
//				DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/news");
//				conn = ds.getConnection();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
	//�ر����ݿ�
	public void closeAll(Connection conn,Statement pstmt,ResultSet rs) {
		try {
			if (rs!=null) {
				rs.close();
			}
			if (pstmt!=null) {
				rs.close();
			}
			if (conn!=null) {
				rs.close();
			}	
		} catch (Exception e) {
			// TODO: handle exception
			e.getStackTrace();
		}
		
	}
	
	/**
	 *  ��ɾ��ͬ�÷���
	 * @param psql Ԥ�����SQL ������? Ҳ����û��?
	 * @param params �������� ��Ҫ��psql��?���� ˳�򱣳�һ��
	 * @return ��Ӱ������
	 */
	public int executeUpdate(String psql,Object[] params) {
		int count=0;
		PreparedStatement pstmt=null;
		
		conn=getConnection();
		try {
			conn=getConnection();
			pstmt=conn.prepareStatement(psql);
			if (params!=null&&params.length>0) {
				for (int i = 0; i < params.length; i++) {
					pstmt.setObject(i+1, params[i]);
				}
			}
			count=pstmt.executeUpdate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			closeAll(conn, pstmt, null);
		}
		return count;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}